package com.dabay.web.util;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.imageio.ImageIO;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.image.codec.jpeg.*;

public class ImagesUtil {
	private static Logger logger = LoggerFactory
			.getLogger(ImagesUtil.class);
	private Image img;
	private int width;
	private int height;
	private String destFileName;
	
	/**
	 * 查找 新闻的图片
	 * @param docUrl 网站上的文章url
	 * @param xx  网站上返回的页面元素
	 * @return
	 */
	public static List<String> getImageList_list(String docUrl,String xx){
		List<String>  imagelist = new ArrayList<String>();
		if(docUrl==null || docUrl=="" || docUrl.trim().length()==0){
			return imagelist;
		}
		List<String> strBuffList = new ArrayList<String>();		
		docUrl = docUrl.substring(0, docUrl.lastIndexOf("/"));
		try {
			String srcReg = "src=\"([^\"]+)\"";
			Pattern p1 = Pattern.compile(srcReg);
			Matcher m = p1.matcher(xx);
			while (m.find()) {
				String str = m.group();
				strBuffList.add(str);

								
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		if(strBuffList.size()>0){
			for (String string : strBuffList) {
				String[] strArray = string.split("src=\"");
				String a1 = strArray[1];
				a1 = a1.substring(0, a1.length()-1);
				imagelist.add(docUrl+"/"+a1);
				
			}
		}		
		//list去重
		List<String> tempList= new ArrayList<String>();  
	    for(String i:imagelist){  
	        if(!tempList.contains(i)){  
	            tempList.add(i);  
	        }  
	    }
		return tempList;		
	}
	
	
	/**
	 * 入数据库 转换为字符串数据
	 * @param imagelist
	 * @return
	 */
	public static String getImageList_String(List<String>  imagelist){	
		if(imagelist.size()==0){
			return "";
		}
		StringBuffer stringbuff = new StringBuffer();
		try {
			if(imagelist.size()>0){
				for (String string : imagelist) {
					stringbuff.append(string+";");
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}				
		return stringbuff.toString();

	}
	//图片下载
	public  static void download(String urlString,String filename,String savePath) throws Exception {
	    // 构造URL
	    URL url = new URL(urlString);
	    // 打开连接
	    URLConnection con = url.openConnection();
	    //设置请求超时为5s
	    con.setConnectTimeout(5*1000);
	    // 输入流
	    InputStream is = con.getInputStream();
	
	    // 1K的数据缓冲
	    byte[] bs = new byte[1024];
	    // 读取到的数据长度
	    int len;
	    // 输出的文件流
	   File sf=new File(savePath);
	   
	   if(!sf.exists()){
		   sf.mkdirs();
	   }
	   OutputStream os = new FileOutputStream(sf.getPath()+"/"+filename);
	    // 开始读取
	    while ((len = is.read(bs)) != -1) {
	      os.write(bs, 0, len);
	    }
	    // 完毕，关闭所有链接
	    os.close();
	    is.close();
	} 
	
	/**
	 * 构造函数
	 */
	public ImagesUtil(String fileName,String destFileNameNew) throws IOException {
		File file = new File(fileName);// 读入文件
		img = ImageIO.read(file);      // 构造Image对象
		width = img.getWidth(null);    // 得到源图宽
		height = img.getHeight(null);  // 得到源图长
		destFileName = destFileNameNew;
	}
	/**
	 * 按照宽度还是高度进行压缩
	 * @param w int 最大宽度
	 * @param h int 最大高度
	 */
	public void resizeFix(int w, int h) throws IOException {
		if (width / height > w / h) {
			resizeByWidth(w);
		} else {
			resizeByHeight(h);
		}
	}
	/**
	 * 以宽度为基准，等比例放缩图片
	 * @param w int 新宽度
	 */
	public void resizeByWidth(int w) throws IOException {
		int h = (int) (height * w / width);
		resize(w, h);
	}
	/**
	 * 以高度为基准，等比例缩放图片
	 * @param h int 新高度
	 */
	public void resizeByHeight(int h) throws IOException {
		int w = (int) (width * h / height);
		resize(w, h);
	}
	/**
	 * 强制压缩/放大图片到固定的大小
	 * @param w int 新宽度
	 * @param h int 新高度
	 */
	public void resize(int w, int h)  {
		try {
			BufferedImage image = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
			image.getGraphics().drawImage(img, 0, 0, w, h, null); // 绘制缩小后的图
			//logger.info("destFileName is ===="+destFileName);
			File destFile = new File(destFileName);
			FileOutputStream out = new FileOutputStream(destFile); // 输出到文件流
			JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
			encoder.encode(image); //
			out.close();
		} catch (Exception e) {
			e.printStackTrace();
			logger.info("resize error======");
			logger.info("resize error  "+e.fillInStackTrace());
		}
	}
	public static boolean checkThisUrlExist(String urlStr){
		boolean result = true;
		InputStream in = null;
		URL url;
		try {
		     url = new URL(urlStr);
		     in = url.openStream();
		} catch (Exception e1) {
		     result = false;
		}finally {
			try {
				if(in!=null){
					in.close();
				}
				return result;
			} catch (IOException e) {
			}
		}
		return result;
	}
	//检查图片的扩展名
	public static boolean checkThisExtendName(String fileName){
		Map extendMap = new HashMap();
		extendMap.put("BMP", "ISOK");
		extendMap.put("JPG", "ISOK");
		extendMap.put("PNG", "ISOK");
		extendMap.put("JPEG", "ISOK");
		extendMap.put("GIF", "ISOK");
		extendMap.put("bmp", "ISOK");
		extendMap.put("jpg", "ISOK");
		extendMap.put("jpeg", "ISOK");
		extendMap.put("png", "ISOK");
		extendMap.put("gif", "ISOK");
		String[] fileArry = fileName.split("\\.");
		if(fileArry!=null && fileArry.length>1){
			  String entendName =fileArry[1];
			  if(extendMap.get(entendName)!=null && extendMap.get(entendName).toString().equals("ISOK")){
				  return true;
			  }
		}
		return false;
	}
}
